package com.hx.zhg.util;

import java.security.MessageDigest;

/** 
 * 不可逆加密算法公共类
 */
public class IrreversibleEncryptionUtil {
	
	/**
	 * MD5密码加密字符串，只适用于用户名密码加密
	 * @return
	 */
	public static String rebuildEncodeMD5(String password) {
		return encodePassword(rebuildPassword(password), "MD5");
	}

	/**
	 * SHA密码加密字符串，只适用于用户名密码加密
	 * @param password
	 * @return
	 */
	public static String rebuildEncodeSHA(String password) {
		return encodePassword(rebuildPassword(password), "SHA");
	}
	
	/**
	 * @Description:传统MD5加密
	 * @param password
	 * @return
	 */
	private static String encodingMD5(String password) {
		return encodePassword(password, "MD5");
	}
	
	/**
	 * @Description:传统SHA加密
	 * @param password
	 * @return
	 */
	private static String encodingSHA(String password) {
		return encodePassword(password, "SHA");
	}
	
	
	/*
	 * 字符编码加密  SHA 或 MD5
	 */
	private static String encodePassword(String password, String algorithm) {
		String processPassword = new StringBuilder(password).reverse().toString();
		byte[] unencodedPassword = processPassword.getBytes();
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance(algorithm);
		} catch (Exception e) {
			return password;
		}
		md.reset();
		md.update(unencodedPassword);
		byte[] encodedPassword = md.digest();
		StringBuilder buf = new StringBuilder();
		for (int i = 0; i < encodedPassword.length; i++) {
			if ((encodedPassword[i] & 0xff) < 0x10) {
				buf.append("0");
			}
			buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
		}
		return buf.toString();
	}

	/*
	 * 将原生密码进行重设
	 */
	private static String rebuildPassword(String password) {
		StringBuilder sb = new StringBuilder();
		char[] c = password.toCharArray();
		for(int i = 0; i < c.length; i++) {
			int temp = (int)c[i] + i + 1;
			sb.append(c[i]).append((char)temp);
		}
		return sb.toString();
	}
}
